package com.small.common.config.db;

import com.small.common.config.admin.IAdminInfo;
import com.small.common.exception.BaseException;
import com.small.common.util.ReflectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 作者: fenny
 * 邮箱: 893146555@qq.com
 * 时间: 2017/10/17 19:04
 * 描述: 实体类相关工具类
 * 解决问题： 1、快速对实体的常驻字段，如：cid、ctime、uid、utime等值快速注入
 */
@Component
public class EntityUtils {

    @Resource
    private IAdminInfo iAdminInfo;

    /**
     * 设置cid、ctime
     *
     * @param entity 实体
     * @param <T>    t
     */
    public <T> void setInsertInfo(T entity) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request != null) {
            // 默认属性
            String[] fields = new String[2];
            fields[0] = "ctime";
            // 默认值
            Object[] value = new Object[2];
            value[0] = System.currentTimeMillis();
            long id = iAdminInfo.getId(request);
            if (id > 0) {
                fields[1] = "cid";
                value[1] = id;
            }
            // 填充默认属性值
            setDefaultValues(entity, fields, value);
        }
    }

    /**
     * 设置uid、utime
     *
     * @param entity 实体bean
     */
    public <T> void setUpdatedInfo(T entity) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if (request != null) {
                // 默认属性
                String[] fields = new String[2];
                fields[0] = "utime";
                // 默认值
                Object[] value = new Object[2];
                value[0] = System.currentTimeMillis();
                long id = iAdminInfo.getId(request);
                if (id > 0) {
                    fields[1] = "uid";
                    value[1] = id;
                }
                // 填充默认属性值
                setDefaultValues(entity, fields, value);
            }
        } catch (Exception e) {
            throw new BaseException(e);
        }
    }

    /**
     * 依据对象的属性数组和值数组对对象的属性进行赋值
     *
     * @param entity 对象
     * @param fields 属性数组
     * @param value  值数组
     */
    private <T> void setDefaultValues(T entity, String[] fields, Object[] value) {
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i];
            if (StringUtils.isNotEmpty(field) && ReflectionUtils.hasField(entity, field)) {
                ReflectionUtils.invokeSetter(entity, field, value[i]);
            }
        }
    }
}
